from django.core.exceptions import PermissionDenied
import re


class StintRequestMiddleware(object):
    def __init__(self, get_response=None):
        print('初始化限制请求中间件...')
        self.get_response = get_response

    def __call__(self, request):
        if 'HTTP_USER_AGENT' in request.META:
            useragent = request.META.get('HTTP_USER_AGENT')
            regex = re.compile(r'.*python.*')
            # TODO: 使用python requests库调用直接抛出异常
            if regex.search(useragent):
                raise PermissionDenied('Forbidden user agent')
            response = self.get_response(request)
            return response
        else:
            # TODO: 未传递User-Agent直接抛出异常
            raise PermissionDenied('Forbidden user agent')

